<template>
  <div class="profile-container">
    <a-row :gutter="24">
      <!-- 个人信息卡片 -->
      <a-col :span="8">
        <a-card title="个人信息">
          <div class="profile-card">
            <div class="avatar-section">
              <a-avatar :size="80" :src="userStore.userInfo?.avatar">
                {{ userStore.userInfo?.realName?.charAt(0) }}
              </a-avatar>
              <a-button type="outline" size="small" @click="showAvatarModal = true">
                更换头像
              </a-button>
            </div>
            
            <div class="info-section">
              <div class="info-item">
                <span class="label">用户名：</span>
                <span class="value">{{ userStore.userInfo?.username }}</span>
              </div>
              <div class="info-item">
                <span class="label">真实姓名：</span>
                <span class="value">{{ userStore.userInfo?.realName }}</span>
              </div>
              <div class="info-item">
                <span class="label">邮箱：</span>
                <span class="value">{{ userStore.userInfo?.email || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="label">手机号：</span>
                <span class="value">{{ userStore.userInfo?.phone || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="label">部门：</span>
                <span class="value">{{ userStore.userInfo?.deptName || '未设置' }}</span>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>

      <!-- 设置面板 -->
      <a-col :span="16">
        <a-card>
          <a-tabs default-active-key="basic" @change="handleTabChange">
            <!-- 基础设置 -->
            <a-tab-pane key="basic" title="基础设置">
              <a-form
                ref="basicFormRef"
                :model="basicForm"
                :rules="basicRules"
                layout="vertical"
                @submit="handleBasicSubmit"
              >
                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-form-item label="真实姓名" field="realName">
                      <a-input v-model="basicForm.realName" placeholder="请输入真实姓名" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="昵称" field="nickname">
                      <a-input v-model="basicForm.nickname" placeholder="请输入昵称" />
                    </a-form-item>
                  </a-col>
                </a-row>

                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-form-item label="邮箱" field="email">
                      <a-input v-model="basicForm.email" placeholder="请输入邮箱" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="手机号" field="phone">
                      <a-input v-model="basicForm.phone" placeholder="请输入手机号" />
                    </a-form-item>
                  </a-col>
                </a-row>

                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-form-item label="性别" field="gender">
                      <a-select v-model="basicForm.gender" placeholder="请选择性别">
                        <a-option :value="1">男</a-option>
                        <a-option :value="2">女</a-option>
                        <a-option :value="0">未知</a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="生日" field="birthday">
                      <a-date-picker
                        v-model="basicForm.birthday"
                        style="width: 100%"
                        placeholder="请选择生日"
                      />
                    </a-form-item>
                  </a-col>
                </a-row>

                <a-form-item label="个人简介" field="intro">
                  <a-textarea
                    v-model="basicForm.intro"
                    placeholder="请输入个人简介"
                    :rows="4"
                    :max-length="500"
                    show-word-limit
                  />
                </a-form-item>

                <a-form-item>
                  <a-button type="primary" html-type="submit" :loading="basicLoading">
                    保存修改
                  </a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>

            <!-- 安全设置 -->
            <a-tab-pane key="security" title="安全设置">
              <a-form
                ref="passwordFormRef"
                :model="passwordForm"
                :rules="passwordRules"
                layout="vertical"
                @submit="handlePasswordSubmit"
              >
                <a-form-item label="原密码" field="oldPassword">
                  <a-input-password
                    v-model="passwordForm.oldPassword"
                    placeholder="请输入原密码"
                  />
                </a-form-item>

                <a-form-item label="新密码" field="newPassword">
                  <a-input-password
                    v-model="passwordForm.newPassword"
                    placeholder="请输入新密码"
                  />
                </a-form-item>

                <a-form-item label="确认密码" field="confirmPassword">
                  <a-input-password
                    v-model="passwordForm.confirmPassword"
                    placeholder="请再次输入新密码"
                  />
                </a-form-item>

                <a-form-item>
                  <a-button type="primary" html-type="submit" :loading="passwordLoading">
                    修改密码
                  </a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>

    <!-- 头像上传弹窗 -->
    <a-modal
      v-model:visible="showAvatarModal"
      title="更换头像"
      width="400px"
      @ok="handleAvatarSubmit"
      @cancel="handleAvatarCancel"
    >
      <div class="avatar-upload">
        <a-upload
          :file-list="avatarFileList"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          @change="handleAvatarChange"
        >
          <div class="upload-area">
            <div v-if="avatarUrl" class="avatar-preview">
              <img :src="avatarUrl" alt="头像预览" />
            </div>
            <div v-else class="upload-placeholder">
              <icon-plus />
              <div>点击上传头像</div>
            </div>
          </div>
        </a-upload>
        <div class="upload-tips">
          <p>支持 jpg、png 格式，文件大小不超过 2MB</p>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { userApi } from '@/api/user'
import { Message } from '@arco-design/web-vue'

const userStore = useUserStore()

// 表单引用
const basicFormRef = ref()
const passwordFormRef = ref()

// 加载状态
const basicLoading = ref(false)
const passwordLoading = ref(false)

// 基础信息表单
const basicForm = reactive({
  realName: '',
  nickname: '',
  email: '',
  phone: '',
  gender: 0,
  birthday: '',
  intro: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 基础信息验证规则
const basicRules = {
  realName: [
    { required: true, message: '请输入真实姓名' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
  ]
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码' },
    { minLength: 6, message: '密码长度至少6位' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码' },
    {
      validator: (value: string, cb: any) => {
        if (value !== passwordForm.newPassword) {
          cb('两次输入的密码不一致')
        } else {
          cb()
        }
      }
    }
  ]
}

// 头像相关
const showAvatarModal = ref(false)
const avatarFileList = ref([])
const avatarUrl = ref('')

// 标签页切换
const handleTabChange = (key: string) => {
  console.log('切换到:', key)
}

// 基础信息提交
const handleBasicSubmit = async () => {
  const errors = await basicFormRef.value?.validate()
  if (errors) return

  basicLoading.value = true
  try {
    await userStore.updateUserInfo(basicForm)
    Message.success('个人信息更新成功')
  } catch (error) {
    Message.error('更新失败')
  } finally {
    basicLoading.value = false
  }
}

// 密码修改提交
const handlePasswordSubmit = async () => {
  const errors = await passwordFormRef.value?.validate()
  if (errors) return

  passwordLoading.value = true
  try {
    await userStore.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    // 重置表单
    Object.assign(passwordForm, {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    passwordFormRef.value?.clearValidate()
  } catch (error) {
    Message.error('密码修改失败')
  } finally {
    passwordLoading.value = false
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    Message.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    Message.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 头像文件改变
const handleAvatarChange = (fileList: any, file: any) => {
  avatarFileList.value = fileList
  
  if (file.file || file) {
    // 创建预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      avatarUrl.value = e.target?.result as string
    }
    reader.readAsDataURL(file.file || file)
  }
}

// 头像提交
const handleAvatarSubmit = async () => {
  if (!avatarFileList.value.length) {
    Message.warning('请选择头像文件')
    return
  }

  try {
    const file = avatarFileList.value[0].file || avatarFileList.value[0]
    await userApi.uploadAvatar(file)
    
    // 刷新用户信息
    await userStore.getUserInfo()
    
    Message.success('头像更新成功')
    showAvatarModal.value = false
    avatarUrl.value = ''
    avatarFileList.value = []
  } catch (error) {
    Message.error('头像上传失败')
  }
}

// 头像弹窗取消
const handleAvatarCancel = () => {
  avatarUrl.value = ''
  avatarFileList.value = []
  showAvatarModal.value = false
}

// 初始化数据
const initData = () => {
  const userInfo = userStore.userInfo
  if (userInfo) {
    Object.assign(basicForm, {
      realName: userInfo.realName || '',
      nickname: userInfo.nickname || '',
      email: userInfo.email || '',
      phone: userInfo.phone || '',
      gender: userInfo.gender || 0,
      birthday: userInfo.birthday || '',
      intro: userInfo.intro || ''
    })
  }
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  .avatar-section {
    text-align: center;
    margin-bottom: 24px;

    .arco-avatar {
      margin-bottom: 12px;
    }
  }

  .info-section {
    .info-item {
      display: flex;
      margin-bottom: 12px;
      
      .label {
        width: 80px;
        color: #86909c;
        flex-shrink: 0;
      }
      
      .value {
        color: #1d2129;
        font-weight: 500;
      }
    }
  }
}

.avatar-upload {
  .upload-area {
    width: 120px;
    height: 120px;
    border: 2px dashed #e5e6eb;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: border-color 0.3s;
    margin: 0 auto 16px;

    &:hover {
      border-color: #165dff;
    }

    .avatar-preview {
      width: 100%;
      height: 100%;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 4px;
      }
    }

    .upload-placeholder {
      text-align: center;
      color: #86909c;
      
      .arco-icon {
        font-size: 24px;
        margin-bottom: 8px;
      }
      
      div {
        font-size: 12px;
      }
    }
  }

  .upload-tips {
    text-align: center;
    
    p {
      color: #86909c;
      font-size: 12px;
      margin: 0;
    }
  }
}
</style> 